/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * PDFAppendDocument.java
 * Copyright (C) 2016-2019 University of Waikato, Hamilton, NZ
 */

package adams.flow.transformer;

import adams.core.ClassCrossReference;
import adams.core.QuickInfoHelper;
import adams.core.Utils;
import adams.core.io.PlaceholderFile;
import adams.flow.control.StorageName;
import adams.flow.control.StorageUser;
import adams.flow.core.Token;
import adams.flow.sink.PDFCloseDocument;
import adams.flow.source.PDFNewDocument;
import adams.flow.transformer.pdfproclet.PDFGenerator;
import adams.flow.transformer.pdfproclet.PdfProclet;

import java.io.File;

/**
 <!-- globalinfo-start -->
 * Modifies the incoming PDF document generated by adams.flow.source.PDFNewDocument using the PDF processors on either the specified input file or storage item.<br>
 * Needs to be finalized with adams.flow.sink.PDFCloseDocument.<br>
 * If a file name is received as input, it is assumed that this is an existing PDF file and gets appended.<br>
 * <br>
 * See also:<br>
 * adams.flow.source.PDFNewDocument<br>
 * adams.flow.sink.PDFCloseDocument
 * <br><br>
 <!-- globalinfo-end -->
 *
 <!-- flow-summary-start -->
 * Input&#47;output:<br>
 * - accepts:<br>
 * &nbsp;&nbsp;&nbsp;adams.flow.transformer.pdfproclet.PDFGenerator<br>
 * &nbsp;&nbsp;&nbsp;java.lang.String<br>
 * &nbsp;&nbsp;&nbsp;java.io.File<br>
 * - generates:<br>
 * &nbsp;&nbsp;&nbsp;adams.flow.transformer.pdfproclet.PDFGenerator<br>
 * <br><br>
 <!-- flow-summary-end -->
 *
 <!-- options-start -->
 * <pre>-logging-level &lt;OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST&gt; (property: loggingLevel)
 * &nbsp;&nbsp;&nbsp;The logging level for outputting errors and debugging output.
 * &nbsp;&nbsp;&nbsp;default: WARNING
 * </pre>
 * 
 * <pre>-name &lt;java.lang.String&gt; (property: name)
 * &nbsp;&nbsp;&nbsp;The name of the actor.
 * &nbsp;&nbsp;&nbsp;default: PDFAppendDocument
 * </pre>
 * 
 * <pre>-annotation &lt;adams.core.base.BaseAnnotation&gt; (property: annotations)
 * &nbsp;&nbsp;&nbsp;The annotations to attach to this actor.
 * &nbsp;&nbsp;&nbsp;default: 
 * </pre>
 * 
 * <pre>-skip &lt;boolean&gt; (property: skip)
 * &nbsp;&nbsp;&nbsp;If set to true, transformation is skipped and the input token is just forwarded 
 * &nbsp;&nbsp;&nbsp;as it is.
 * &nbsp;&nbsp;&nbsp;default: false
 * </pre>
 * 
 * <pre>-stop-flow-on-error &lt;boolean&gt; (property: stopFlowOnError)
 * &nbsp;&nbsp;&nbsp;If set to true, the flow execution at this level gets stopped in case this 
 * &nbsp;&nbsp;&nbsp;actor encounters an error; the error gets propagated; useful for critical 
 * &nbsp;&nbsp;&nbsp;actors.
 * &nbsp;&nbsp;&nbsp;default: false
 * </pre>
 * 
 * <pre>-silent &lt;boolean&gt; (property: silent)
 * &nbsp;&nbsp;&nbsp;If enabled, then no errors are output in the console; Note: the enclosing 
 * &nbsp;&nbsp;&nbsp;actor handler must have this enabled as well.
 * &nbsp;&nbsp;&nbsp;default: false
 * </pre>
 * 
 * <pre>-proclet &lt;adams.flow.transformer.pdfproclet.PdfProclet&gt; [-proclet ...] (property: proclets)
 * &nbsp;&nbsp;&nbsp;The processors for processing the data (file or storage item).
 * &nbsp;&nbsp;&nbsp;default: 
 * </pre>
 * 
 * <pre>-type &lt;FILE|STORAGE&gt; (property: type)
 * &nbsp;&nbsp;&nbsp;The type of data to process.
 * &nbsp;&nbsp;&nbsp;default: FILE
 * </pre>
 * 
 * <pre>-input-file &lt;adams.core.io.PlaceholderFile&gt; (property: inputFile)
 * &nbsp;&nbsp;&nbsp;The file to process by the PDF processors.
 * &nbsp;&nbsp;&nbsp;default: ${CWD}
 * </pre>
 * 
 * <pre>-storage-name &lt;adams.flow.control.StorageName&gt; (property: storageName)
 * &nbsp;&nbsp;&nbsp;The name of the storage item to retrieve.
 * &nbsp;&nbsp;&nbsp;default: storage
 * </pre>
 * 
 <!-- options-end -->
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 */
public class PDFAppendDocument
  extends AbstractTransformer
  implements ClassCrossReference, StorageUser {

  private static final long serialVersionUID = 6232379845991992764L;

  /**
   * Determines whether to load the data from a file or from storage.
   *
   * @author FracPete (fracpete at waikato dot ac dot nz)
   * @version $Revision$
   */
  public enum DataType {
    FILE,
    STORAGE
  }

  /** the PDF processors. */
  protected PdfProclet[] m_Proclets;

  /** the data type. */
  protected DataType m_Type;

  /** the file to process. */
  protected PlaceholderFile m_InputFile;

  /** the storage item to use. */
  protected StorageName m_StorageName;

  /**
   * Returns a string describing the object.
   *
   * @return 			a description suitable for displaying in the gui
   */
  @Override
  public String globalInfo() {
    return
      "Modifies the incoming PDF document generated by " + PDFNewDocument.class.getName()
	+ " using the PDF processors on either the specified input file or storage item.\n"
	+ "Needs to be finalized with " + PDFCloseDocument.class.getName() + ".\n"
	+ "If a file name is received as input, it is assumed that this is an existing "
	+ "PDF file and gets appended.";
  }

  /**
   * Returns the cross-referenced classes.
   *
   * @return		the classes
   */
  public Class[] getClassCrossReferences() {
    return new Class[]{
      PDFNewDocument.class,
      PDFCloseDocument.class
    };
  }

  /**
   * Adds options to the internal list of options.
   */
  @Override
  public void defineOptions() {
    super.defineOptions();

    m_OptionManager.add(
      "proclet", "proclets",
      new PdfProclet[0]);

    m_OptionManager.add(
      "type", "type",
      DataType.FILE);

    m_OptionManager.add(
      "input-file", "inputFile",
      new PlaceholderFile("."));

    m_OptionManager.add(
      "storage-name", "storageName",
      new StorageName());
  }

  /**
   * Sets the processors to use.
   *
   * @param value	the processors to use
   */
  public void setProclets(PdfProclet[] value) {
    m_Proclets = value;
    reset();
  }

  /**
   * Returns the processors in use.
   *
   * @return 		the processors in use
   */
  public PdfProclet[] getProclets() {
    return m_Proclets;
  }

  /**
   * Returns the tip text for this property.
   *
   * @return         tip text for this property suitable for
   *             displaying in the GUI or for listing the options.
   */
  public String procletsTipText() {
    return "The processors for processing the data (file or storage item).";
  }

  /**
   * Sets the type of data to use.
   *
   * @param value	the type
   */
  public void setType(DataType value) {
    m_Type = value;
    reset();
  }

  /**
   * Returns the type of data to use.
   *
   * @return 		the type
   */
  public DataType getType() {
    return m_Type;
  }

  /**
   * Returns the tip text for this property.
   *
   * @return         tip text for this property suitable for
   *             displaying in the GUI or for listing the options.
   */
  public String typeTipText() {
    return "The type of data to process.";
  }

  /**
   * Sets the input file to process.
   *
   * @param value	the file
   */
  public void setInputFile(PlaceholderFile value) {
    m_InputFile = value;
    reset();
  }

  /**
   * Returns the input file to process.
   *
   * @return 		the file
   */
  public PlaceholderFile getInputFile() {
    return m_InputFile;
  }

  /**
   * Returns the tip text for this property.
   *
   * @return         tip text for this property suitable for
   *             displaying in the GUI or for listing the options.
   */
  public String inputFileTipText() {
    return "The file to process by the PDF processors.";
  }

  /**
   * Sets the name of the storage item to retrieve.
   *
   * @param value	the storage item
   */
  public void setStorageName(StorageName value) {
    m_StorageName = value;
    reset();
  }

  /**
   * Returns the name of the storage item to retrieve.
   *
   * @return 		the storage item
   */
  public StorageName getStorageName() {
    return m_StorageName;
  }

  /**
   * Returns the tip text for this property.
   *
   * @return         tip text for this property suitable for
   *             displaying in the GUI or for listing the options.
   */
  public String storageNameTipText() {
    return "The name of the storage item to retrieve.";
  }

  /**
   * Returns whether storage items are being used.
   *
   * @return		true if storage items are used
   */
  public boolean isUsingStorage() {
    return !m_Skip && (m_Type == DataType.STORAGE);
  }

  /**
   * Returns the class that the consumer accepts.
   *
   * @return		the Class of objects that can be processed
   */
  @Override
  public Class[] accepts() {
    return new Class[]{PDFGenerator.class, String.class, File.class};
  }

  /**
   * Returns the class of objects that it generates.
   *
   * @return		the Class of the generated tokens
   */
  @Override
  public Class[] generates() {
    return new Class[]{PDFGenerator.class};
  }

  /**
   * Returns a quick info about the actor, which will be displayed in the GUI.
   *
   * @return		null if no info available, otherwise short string
   */
  @Override
  public String getQuickInfo() {
    String	result;

    result  = QuickInfoHelper.toString(this, "type", m_Type, "type: ");
    result += QuickInfoHelper.toString(this, "inputFile", m_InputFile, ", input: ");
    result += QuickInfoHelper.toString(this, "storageName", m_StorageName, ", storage: ");
    result += QuickInfoHelper.toString(this, "proclets", m_Proclets, ", processors: ");

    return result;
  }

  /**
   * Executes the flow item.
   *
   * @return		null if everything is fine, otherwise error message
   */
  @Override
  protected String doExecute() {
    String		result;
    PDFGenerator	generator;
    PlaceholderFile	file;
    Object		obj;

    result = null;

    obj = null;
    switch (m_Type) {
      case FILE:
	if (m_InputFile.isDirectory())
	  result = "Input file points to a directory: " + m_InputFile;
	break;

      case STORAGE:
	obj = getStorageHandler().getStorage().get(m_StorageName);
	if (obj == null)
	  result = "Storage item not available: " + m_StorageName;
	break;

      default:
	throw new IllegalStateException("Unhandled data type: " + m_Type);
    }

    generator = null;
    file      = null;
    if (result == null) {
      if (m_InputToken.getPayload() instanceof String)
	file = new PlaceholderFile((String) m_InputToken.getPayload());
      else if (m_InputToken.getPayload() instanceof File)
	file = new PlaceholderFile((File) m_InputToken.getPayload());
      else if (m_InputToken.getPayload() instanceof PDFGenerator)
	generator = (PDFGenerator) m_InputToken.getPayload();
      else
        result = "Unhandled input type: " + Utils.classToString(m_InputToken.getPayload());

      if (file != null) {
	try {
	  generator = new PDFGenerator();
	  generator.setLoggingLevel(getLoggingLevel());
	  generator.setOutput(file);
	  generator.append();
	}
	catch (Exception e) {
	  result = handleException("Failed to append PDF document '" + file + "'!", e);
	}
      }
    }

    if (result == null) {
      for (PdfProclet proclet : m_Proclets) {
	try {
	  switch (m_Type) {
	    case FILE:
	      if (proclet.canProcess(generator, m_InputFile))
		proclet.process(generator, m_InputFile);
	      break;

	    case STORAGE:
	      if (proclet.canProcess(generator, obj))
		proclet.process(generator, obj);
	      break;

	    default:
	      throw new IllegalStateException("Unhandled data type: " + m_Type);
	  }
	}
	catch (Exception e) {
	  result = handleException("Failed to apply processor: " + proclet.toCommandLine(), e);
	}
      }
      m_OutputToken = new Token(generator);
    }

    return result;
  }
}
